package com.imut.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imut.oa.common.ErrorCode;
import com.imut.oa.common.PageResult;
import com.imut.oa.exception.BusinessException;
import com.imut.oa.mapper.NoticeMapper;
import com.imut.oa.pojo.dto.NoticeAddDTO;
import com.imut.oa.pojo.dto.NoticePageQueryDTO;
import com.imut.oa.pojo.entity.Notice;
import com.imut.oa.pojo.vo.ExpenseVO;
import com.imut.oa.pojo.vo.NoticeVO;
import com.imut.oa.service.NoticeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
    @Resource
    private NoticeMapper noticeMapper;

    /**
     * 公告分页查询
     * @param noticePageQueryDTO
     * @return
     */
    @Override
    public PageResult page(NoticePageQueryDTO noticePageQueryDTO) {
        Page<NoticeVO> page = new Page<>(noticePageQueryDTO.getPage(), noticePageQueryDTO.getPageSize());
        // 调用自定义的联表分页查询
        Page<NoticeVO> voPage = noticeMapper.selectNoticePage(page, noticePageQueryDTO);
        System.out.println(voPage.getRecords());
        System.out.println(voPage);
        return new PageResult(voPage.getTotal(), voPage.getRecords());
    }

    /**
     * 公告添加
     * @param noticeAddDTO
     */
    @Override
    public void save(NoticeAddDTO noticeAddDTO) {
        if (noticeAddDTO.getTitle() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "公告标题不能为空");
        }

        if (noticeAddDTO.getContent() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "公告内容不能为空");
        }

        Notice notice = Notice.builder()
                .title(noticeAddDTO.getTitle())
                .content(noticeAddDTO.getContent())
                .isDelete(0)
                .build();

        noticeMapper.customInsert(notice);
    }

    /**
     * 根据ID删除公告
     * @param id
     */
    @Override
    public void removeNoticeById(Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "公告ID不能为空");
        }

        UpdateWrapper<Notice> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("isDelete", 1);

        noticeMapper.update(updateWrapper);
    }

    @Override
    public List<Notice> getNoticeHistory(int page, int pageSize) {
        int offset = (page - 1) * pageSize;
        return noticeMapper.getNoticeHistory(offset, pageSize);
    }
}